<template>
  <div class="demo-tree">
    <div class="custom-tree-container">
      <div class="block">
        <p>使用 tree</p>
        <!--
        http://element-cn.eleme.io/#/zh-CN/component/tree
        Attributes  props
                :load="loadNode"
                :data="treeData"
    <el-tree
                :props="props1"
                :load="loadNode"
                show-checkbox   节点是否可被选择
                lazy
                @node-click="handleNodeClick"
                @check-change="handleCheckChange"

                node-key="id"
                default-expand-all                是否默认展开所有节点
                :expand-on-click-node="false"     点击节点的时候展开或者收缩节点
                @node-drag-start="handleDragStart"
                @node-drag-enter="handleDragEnter"
                @node-drag-leave="handleDragLeave"
                @node-drag-over="handleDragOver"
                @node-drag-end="handleDragEnd"
                @node-drop="handleDrop"
                draggable
                :allow-drop="allowDrop" 拖拽时判定目标节点能否被放置。type 参数有三种情况：'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
                :allow-drag="allowDrag" 判断节点能否被拖拽
                  @node-drag-over="handleDragOver"

        >-->
        <el-tree ref="treeRef"
                 :props="props1"
                 :data="treeData"
                 show-checkbox
                 :lazy="true"
                 :load="loadNode"
                 node-key="id"
                 expand-on-click-node
        >
          <span class="custom-tree-node newbi" slot-scope="{ node, data }">
          <span><i v-show="node.data.isLeaf" class="el-icon-info"> </i>&nbsp;{{ node.label }}</span>
          <span class="tree-diy">{{ node.id }}</span>
          <span class="tree-diy">{{ node.isLeaf }}</span>
          <span class="tree-diy">{{ node.data.id }}</span>
          <span class="tree-diy">{{ node.data.groupName }}</span>
          <span>
            <template v-if="node.data.isLeaf">
                <i class="el-icon-edit" @click.stop="() => editResource(data)"></i>
            &nbsp;&nbsp;<i class="el-icon-delete" @click.stop="() => removeR(node, data)"></i>
            </template>
            <template v-else>
              <i v-if="node.data.groupEnd" class="el-icon-circle-plus-outline"
                 @click.stop="() => createLeaf(data)"></i>
              &nbsp;&nbsp;<i class="el-icon-plus" @click.stop="() => createG(data)"></i>
              &nbsp;&nbsp;<i class="el-icon-edit" @click.stop="() => editGroup(data)"></i>
              &nbsp;&nbsp;<i class="el-icon-delete" @click.stop="() => removeG(node, data)"></i>
              <!--<el-button  icon="el-icon-plus" circle type="success" size="mini" @click="() => append(data)"> </el-button>-->
            </template>
          </span>
        </span>
        </el-tree>
      </div>
    </div>
    <!---->
    <el-dialog :title="textMap2[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px"
               style='width: 450px; margin-left:50px;'>


        <el-form-item label="资源名" prop="resourceName">
          <el-input v-model="leafTemp.resourceName"></el-input>
        </el-form-item>
        <el-form-item label="资源类型" prop="resourceType">
          <el-select v-model="leafTemp.resourceType" placeholder="请选择">
            <el-option
              v-for="item in resourceType"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>

          <!--<el-input v-model="leafTemp.resourceType"></el-input>-->
        </el-form-item>
        <el-form-item label="请求方法" prop="requestMethod">
          <el-select v-model="leafTemp.requestMethod" placeholder="请选择">
            <el-option
              v-for="item in requestMethod"
              :key="item"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
          <!--<el-input v-model="leafTemp.requestMethod"></el-input>-->
        </el-form-item>
        <el-form-item label="资源码" prop="resourceCode" placeholder="resourceCode">
          <el-input v-model="leafTemp.resourceCode"></el-input>
        </el-form-item>
        <el-form-item label="图标链接" prop="icon" placeholder="icon">
          <el-input v-model="leafTemp.icon"></el-input>
        </el-form-item>
        <el-form-item label="标记" prop="tag" placeholder="tag">
          <el-input v-model="leafTemp.tag"></el-input>
        </el-form-item>
        <el-form-item label="url" prop="url">
          <el-input v-model="leafTemp.url"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createLeafSubmit" id="cfmbtm1">确定
        </el-button>
        <el-button v-else type="primary" @click="editLeaf" id="cfmbtm2">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  //http://extjs.org.cn/
  //http://element-cn.eleme.io/#/zh-CN/component/tree
  import {fetchList, fetchGet, createOne, deleteOne, getOne, rolesAll, updateOneNoId} from '@/api/common'
  import {disableBtn, df, $err, $suc, ERRS, SUCS} from '@/utils'

  export default {
    inject: ['reload'],
    name: 'tree',
    props: {
      /*        fdata: {
                  type: Array,
                  default() {
                      return []
                  }
              },*/
    },
    data() {
      /*const data = ;*/
      return {
        // treeData:this.fdata,
        url: 'security/resourceGroups',
        urlLeaf: 'security/resources',
        treeData: [],
        nodeData: {},
        props1: { //自定义数组属性 leaf 叶子节点
          id: 'id',
          label: 'groupName',
          children: 'children',
          isLeaf: 'isLeaf',
        },
        count: 3,
        //弹出层
        dialogFormVisible: false,
        dialogStatus: '',
        listLoading: true,
        textMap: {
          update: '编辑资源组',
          create: '添加资源组'
        },
        textMap2: {
          update: '编辑资源',
          create: '添加资源'
        },
        requestMethod: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'TRACE', 'ALL', 'NOAPI'],
        resourceType: ['WEB_MENU', 'WEB_BUTTON', 'ANDROID_MENU', 'ANDROID_BUTTON', 'IOS_MENU', 'IOS_BUTTON',],
        temp: {},
        leafTemp: {},
        template: {
          id: undefined,
          roleName: '',
          roleCode: ''
        },
        rules: {
          roleName: [
            {required: true, message: '请输入角色名', trigger: 'blur'}
          ],
          roleCode: [
            {required: true, message: '请输入标记名', trigger: 'change'},
          ]
        }
        // data5: JSON.parse(JSON.stringify(this.trees))
      }
    },

    mounted() {
      // this.getList();
      // this.initInfo();
    },
    computed: {},
    methods: {
      /*  ----------curd ----------- */
      //添加资源组
      appendG(data) {
        df(222, data)
        const newChild = {
          id: ++this.count, name: 'testtest', children: [],
          groupEnd: true
        };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
        data.groupEnd = false;

        df(222, data)
        df(222, this.treeData)
      },

      createG() {
        this.resetTemp();
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      //添加提交
      createGsubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm1');
            createOne(this.url, this.temp).then(res => {

              // this.reload();
              this.dialogFormVisible = false
              succ('创建成功')
            })
          }
        })
      },


      //添加资源(叶子)
      appendLeaf(data) {
        const newChild = {
          id: ++this.count, name: 'testtest', children: [],
          groupEnd: false
        };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
        data.groupEnd = false;

        df('11append', this.treeData)
      },
      createLeaf(data) {
        console.log(257, data)
        this.nodeData = data
        this.leafTemp = {
          groupId: data.id,
          id: "",
          icon: "",
          requestMethod: "",
          resourceType: "",
          resourceCode: "",
          resourceName: "",
          tag: "",
          url: ""
        };
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      //添加提交
      createLeafSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            disableBtn('cfmbtm1');
            console.log(277, this.leafTemp)
            let lf = this.leafTemp;
            const params = new URLSearchParams();
            params.append('icon', lf.icon);
            params.append('requestMethod', lf.requestMethod);
            params.append('resourceType', lf.resourceType);
            params.append('resourceCode', lf.resourceCode);
            params.append('resourceName', lf.resourceName);
            params.append('tag', lf.tag);
            params.append('url', lf.url);
            createOne(`security/resources/groups/${this.leafTemp.groupId}/resources`, params).then(response => {

              if (res.data.code === 0) {
                //根据 data 或者 key 拿到 Tree 组件中的 node
                let node = this.$refs.treeRef.getNode(this.nodeData);

                this.leafTemp.groupName = this.leafTemp.resourceName
                this.leafTemp.isLeaf = true
                this.leafTemp.id = '' //todo id
                if (!node.data.children) {
                  this.$set(node.data, 'children', []);
                }
                node.data.children.push(this.leafTemp)
                // this.reload();
                this.dialogFormVisible = false
                succ('创建成功')
                // this.reload()
              } else {
                $err(res.data.message)
              }

            })
          }
        })
      },
      removeG(node, data) {
        // df('rm G', node.data.id, node)
        this.remove(node, data, ' 资源组及子资源 ', this.url)
      },
      removeR(node, data) {
        df('rm R', node, data)
        this.remove(node, data, ' 资源 ', this.urlLeaf)
      },
      remove(node, data, msg, url) {
        this.$msgbox({
          message: `确定要删除该${msg}吗?`,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(action => {
          deleteOne(url, {id: node.data.id}).then(res => {
            df(5435345, res)
            if (res.data.code === 0) {
              const parent = node.parent;
              const children = parent.childNodes || parent.data;
              const index = children.findIndex(d => d.data.id === data.id);
              df('6435345', index)
              children.splice(index, 1);
              $suc('删除成功')
              // this.reload()
            } else {
              $err(res.data.message)
            }
          })
        });
      },

      //详情修改
      editLeaf(data) {
        df('editResource', data);
        /*            this.temp=row;
                    this.dialogFormVisible = true;
                    this.$nextTick(() => {
                        this.$refs['dataForm'].clearValidate()
                    })*/
      },
      editGroup(data) {
        df('editGroup', data);
        return false;
      },
      /*            getList() {
                      this.listLoading = true;
                      // fetchList(`security/resourceGroups/root`).then(response => {
                      // fetchList(`security/resourceGroups`).then(response => {
                      fetchList(`security/resourceGroups/resourceRG/all`).then(response => {
                          let data=response.data;
                          console.log(100,data)
                          if(data.code==0){
                              // return data.data
                              this.treeData= data.data

                              this.$nextTick(function(){
                                  console.log('v-for渲染已经完成')
                                  // this.loadNode()
                              })
                          }else{
                              err(data.message)
                          }
                          this.listLoading = false
                      })
                  },*/
      handleCheckChange(data, checked, indeterminate) {
        console.log(data, checked, indeterminate);
      },
      //节点点击事件
      handleNodeClick(data) {
        console.log(data);
        // this.append(data)
      },
      loadNode(node, resolve) {
        console.log('loadNode', node);
        //1级组节点
        if (node.level === 0) {
          fetchList(`security/resourceGroups/root`).then(response => {
            // fetchList(`security/resourceGroups/resourceRG/all`).then(response => {
            let data = response.data;
            // console.log(100,data)
            if (data.code == 0) {
              // console.log(555,this.treeData)
              // node.level=
              let ret = data.data.map((v, index) => {
                v.isLeaf = false
                return v
              });
              // this.treeData= ret
              console.log('trrrrr', this.treeData);
              console.log(node);
              return resolve(ret);
            } else {
              err(data.message)
            }
          })
        } else {
          df(99898, node.data)
          let qid = node.data.id;
          //组子节点(含子节点)
          if (node.data.groupEnd === false) {
            fetchList('security/resourceGroups/parentId/' + qid).then(response => {
              let data = response.data;
              console.log(110, data)
              if (data.code == 0) {

                console.log(112, node)
                let ret = data.data.map((v, index) => {
                  v.isLeaf = false
                  return v
                });
                resolve(ret); //加载下级数据!
              } else {
                err(data.message)
                return resolve([]);
              }
            })
          } else if (node.data.groupEnd === true) {
            df(220, node)
            //组子节点(叶子)
            //叶子调用资源
            fetchList('security/resources/groups/' + qid).then(response => {
              let data = response.data;
              // console.log(221,data)
              if (data.code == 0) {
                let da = data.data
                let ret = data.data.map((v, index) => {
                  v.groupName = v.resourceName
                  v.isLeaf = true
                  return v
                });
                // console.log(222,ret)

                return resolve(ret); //加载下级数据!
              } else {
                err(data.message)
                return resolve([]);
              }
            })
            resolve([]);
          } else {
            // df(130,node)
            return resolve([]);

          }
        }
      },


    },
  }
</script>

<style scoped>

  .demo-tree {
    background: #f6f6f6
  }

  .demo-tree .buttons, .demo-tree .filter-tree {
    margin-top: 20px
  }

  .demo-tree .custom-tree-container {
    display: -ms-flexbox;
    display: flex;
    margin: 0px
  }

  .demo-tree .block {
    -ms-flex: 1;
    flex: 1;
    padding: 8px 24px 24px
  }

  .demo-tree .block > p {
    text-align: center;
    margin: 0;
    line-height: 4
  }

  .demo-tree .block:first-child {
    border-right: 1px solid #eff2f6
  }

  .demo-tree .custom-tree-node {
    -ms-flex: 1;
    flex: 1;
    display: -ms-flexbox;
    display: flex;
    -ms-flex-align: center;
    align-items: center;
    -ms-flex-pack: justify;
    justify-content: space-between;
    font-size: 16px;
    padding: 8px;
  }

  .demo-tree .el-tree {
    border: 1px solid #fbd7ff;
    border-radius: 5px;
    padding: 10px;
  }

  .demo-tree .el-tree-node__content {
  }

  #app .demo-tree .el-tree .el-tree-node {
    background: greenyellow !important;
  }

  .newbi {
    /*border-bottom:1px solid #bade28 !important;*/
    /*border-top:1px solid #bade28 !important;*/
  }
</style>
